package cConfig

import (
	"fmt"
	"reflect"
	"strings"

	"gitee.com/csingo/cComponents"
	"gitee.com/csingo/cHelper"
)

func GetConf(name string) (any, error) {
	var config any

	splits := strings.Split(name, ".")
	length := len(splits)

	if length == 0 {
		return nil, fmt.Errorf("config name is invalid")
	}

	instance := container.Get(splits[0]).(cComponents.ConfigInterface)
	if instance == nil {
		return nil, fmt.Errorf("config is not exists")
	}

	config = instance

	var current reflect.Value
	for _, item := range splits[1:] {
		if cHelper.IsNumber(item) {
			index := cHelper.ToInt(item)
			current = reflect.ValueOf(config).Index(index)
			if !current.IsValid() || (current.Kind() == reflect.Ptr && current.IsNil()) {
				config = nil
				break
			}
			config = current.Interface()
		} else {
			current = reflect.ValueOf(config)
			if current.Kind() == reflect.Ptr {
				current = current.Elem().FieldByName(item)
			} else {
				current = current.FieldByName(item)
			}
			if !current.IsValid() || (current.Kind() == reflect.Ptr && current.IsNil()) {
				config = nil
				break
			}
			config = current.Interface()
		}
	}

	return config, nil
}
